/**
 * 自定义API测试脚本，专注于测试token获取
 */

import fs from 'fs';
import path from 'path';
import http from 'http';
import https from 'https';
import { fileURLToPath } from 'url';

// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 加载配置
const loadConfig = () => {
    try {
        const configPath = path.join(__dirname, 'env.config');
        const content = fs.readFileSync(configPath, 'utf8');
        const config = {};

        content.split('\n').forEach(line => {
            if (line.trim().startsWith('#') || !line.trim()) return;

            const match = line.match(/^([A-Z0-9_]+)="([^"]*)"/);
            if (match) {
                const [, key, value] = match;
                config[key] = value;
            }
        });

        return config;
    } catch (error) {
        console.error('加载配置文件失败:', error);
        process.exit(1);
    }
};

// 发送HTTP请求
const sendRequest = (url, method = 'GET', headers = {}, body = null) => {
    return new Promise((resolve, reject) => {
        try {
            const parsedUrl = new URL(url);
            const options = {
                hostname: parsedUrl.hostname,
                port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
                path: parsedUrl.pathname + parsedUrl.search,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    ...headers
                },
                timeout: 5000 // 5秒超时
            };

            console.log(`发送${method}请求到: ${url}`);
            console.log(`请求头:`, JSON.stringify(headers, null, 2));
            if (body) {
                console.log(`请求体:`, JSON.stringify(body, null, 2));
            }

            const client = parsedUrl.protocol === 'https:' ? https : http;
            const req = client.request(options, (res) => {
                let data = '';

                res.on('data', (chunk) => {
                    data += chunk;
                });

                res.on('end', () => {
                    console.log(`状态码: ${res.statusCode}`);

                    // 尝试解析JSON
                    let parsedData = null;
                    let parseError = null;

                    if (data) {
                        try {
                            parsedData = JSON.parse(data);
                            console.log('完整响应:', JSON.stringify(parsedData, null, 2));
                        } catch (error) {
                            parseError = error;
                            console.log('原始响应:', data);
                        }
                    }

                    resolve({
                        statusCode: res.statusCode,
                        headers: res.headers,
                        data: parsedData,
                        rawData: data,
                        parseError: parseError
                    });
                });
            });

            req.on('error', (error) => {
                console.error(`请求失败: ${error.message}`);
                reject(error);
            });

            req.on('timeout', () => {
                console.error('请求超时');
                req.destroy();
                reject(new Error('请求超时'));
            });

            if (body) {
                req.write(typeof body === 'string' ? body : JSON.stringify(body));
            }

            req.end();
        } catch (error) {
            console.error(`创建请求失败: ${error.message}`);
            reject(error);
        }
    });
};

// 测试不同的token请求格式
const testTokenRequest = async () => {
    const config = loadConfig();
    const baseUrl = config.AUTO_API_BASE_URL;

    console.log('API基础URL:', baseUrl);
    console.log('项目ID:', config.PROJECT_ID);

    const tokenUrl = `${baseUrl}/get_token`;

    // 测试不同的请求体格式
    const requestFormats = [
        {
            label: '标准格式',
            body: {
                project_id: config.PROJECT_ID
            }
        },
        {
            label: '带schema',
            body: {
                project_id: config.PROJECT_ID,
                schema: config.SCHEMA_NAME
            }
        },
        {
            label: '小写project_id',
            body: {
                projectid: config.PROJECT_ID
            }
        },
        {
            label: '驼峰projectId',
            body: {
                projectId: config.PROJECT_ID
            }
        },
        {
            label: '字符串格式',
            body: JSON.stringify({
                project_id: config.PROJECT_ID
            })
        },
        {
            label: '空请求体',
            body: null
        }
    ];

    for (const format of requestFormats) {
        console.log(`\n===== 测试 ${format.label} =====`);

        try {
            const response = await sendRequest(tokenUrl, 'POST', {}, format.body);

            if (response.statusCode >= 200 && response.statusCode < 300 && response.data) {
                console.log('请求成功!');

                // 如果成功获取令牌，保存到文件
                if (response.data.data && response.data.data.token) {
                    const token = response.data.data.token;
                    const tokenPath = path.join(__dirname, 'token.json');
                    fs.writeFileSync(tokenPath, JSON.stringify({ token }, null, 2));
                    console.log(`令牌已保存到: ${tokenPath}`);

                    // 停止测试，因为我们找到了正确的格式
                    return true;
                }
            } else {
                console.log('请求失败');
            }
        } catch (error) {
            console.error('请求错误:', error);
        }
    }

    return false;
};

// 测试特殊的端点路径
const testSpecialEndpoints = async () => {
    const config = loadConfig();
    const baseHost = `http://${new URL(config.AUTO_API_BASE_URL).hostname}:${new URL(config.AUTO_API_BASE_URL).port}`;

    console.log('\n===== 测试特殊端点 =====');

    const endpoints = [
        `${baseHost}/login`,
        `${baseHost}/token`,
        `${baseHost}/auth`,
        `${baseHost}/api/login`,
        `${baseHost}/api/token`,
        `${baseHost}/api/v1/token`,
        `${baseHost}/api/auth`,
        `${baseHost}/tls/token`,
        `${baseHost}/autoapi/token`
    ];

    for (const endpoint of endpoints) {
        console.log(`\n测试: ${endpoint}`);

        try {
            const response = await sendRequest(endpoint, 'GET');

            if (response.statusCode >= 200 && response.statusCode < 300 && !response.parseError) {
                console.log('端点可能有效!');
            }
        } catch (error) {
            console.error('请求错误:', error);
        }
    }
};

// 主函数
const main = async () => {
    console.log('=== 自定义API测试开始 ===');

    const success = await testTokenRequest();

    if (!success) {
        console.log('\n未能找到有效的token请求格式，尝试测试特殊端点...');
        await testSpecialEndpoints();
    }

    console.log('\n=== 测试完成 ===');
};

// 执行主函数
main().catch(error => {
    console.error('测试过程中发生错误:', error);
    process.exit(1);
}); 